<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 头部 -->
        <TreeTools :node-data="company" :is-root="true" @showDialog="showDialog" />

        <!-- 树形组件渲染 -->
        <!-- https://element.eleme.cn/#/zh-CN/component/tree#scoped-slot -->
        <!-- default-expand-all 展开tree -->
        <el-tree :data="list" :props="defaultProps" default-expand-all>
          <!-- 这里的data已经将数组拆分，将一个个对象拿了出来 -->
          <template #default="{data}">
            <TreeTools :node-data="data" @showDialog="showDialog" />
          </template>
        </el-tree>

        <!-- 弹窗 -->
        <el-dialog
          ref="departRef"
          title="添加子部门"
          :visible="dialogVisible"
          width="40%"
          @close="closeDialog"
          @open="openDialog"
        >
          <!-- 表单内容 -->
          <!-- https://element.eleme.cn/#/zh-CN/component/form -->
          <el-form ref="departRef" :model="departForm" :rules="departRules" label-width="120px">
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="departForm.name" style="width:80%" placeholder="1-50个字符" />
            </el-form-item>
            <el-form-item label="部门编码" prop="code">
              <el-input v-model="departForm.code" style="width:80%" placeholder="1-50个字符" />
            </el-form-item>
            <el-form-item label="部门负责人" prop="manager">
              <el-select
                v-model="departForm.manager"
                style="width:80%"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in managerList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.username"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="部门介绍" prop="introduce">
              <el-input v-model="departForm.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" />
            </el-form-item>
          </el-form>
          <!-- 底部按钮 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>

    </div>
  </div>
</template>

<script>
import TreeTools from './components/TreeTools.vue'
import { getDepartment, getDepartDetail } from '@/api/department.js'
import { getMangerList, addDepartment } from '@/api/employee.js'
import transTree from '@/utils/transTree'
export default {
  name: 'Dashboard',
  components: { TreeTools },
  data() {
    // 部门名称自定义校验规则
    const validateName = (rules, value, cb) => {
      // 1. 找到所有的同级部门
      // 以 this.nodeData.id 作为父亲，找他所有的孩子
      const broArr = this.originList.filter(item => item.pid === this.nodeData.id)
      // 2. 只要当前添加的部门名称和任意一个同级部门的名称相等，就不通过校验
      const isSame = broArr.some(item => item.name === value)
      if (isSame) {
        // 校验不通过
        cb(new Error('同级部门名称不能重复！'))
      } else {
        // 校验通过
        cb()
      }
    }

    // 部门编码自定义校验规则
    const validateCode = (rules, value, cb) => {
      // 在所有部门中，找是否存在相同的部门编码
      const isSame = this.originList.some(item => item.code === value)
      isSame ? cb(new Error('部门编码不能重复')) : cb()
    }

    return {
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      company: { name: '江苏传智播客教育科技股份有限公司', manager: '负责人', id: '' },
      dialogVisible: false, // 控制弹窗的显示与隐藏
      departForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      departRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      // 正在操作的部门,子传递父拿到
      nodeData: {},

      originList: [],
      managerList: []
    }
  },
  created() {
    this.fetchDepartment()
  },
  methods: {
    // 获取树状结构列表数据
    async fetchDepartment() {
      const res = await getDepartment()
      this.list = transTree(res.depts)
      this.company.name = res.companyName
    },
    // 打开弹窗
    showDialog(nodeData, type) {
      this.dialogVisible = true
      this.nodeData = nodeData
      if (type === 'edit') {
        this.getDetail()
      }
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
      this.$refs.departRef.resetFields()
    },
    // 弹窗打开后执行回调
    async openDialog() {
      const res = await getMangerList()
      this.managerList = res
      // console.log(res)
    },
    // 点击提交
    submit() {
      // 关闭弹窗
      this.dialogVisible = false
      this.$refs.departRef.validate(async valid => {
        if (!valid) return

        await addDepartment({ ...this.departForm, pid: this.nodeData.id })
        this.$message.success('新增成功')
        this.closeDialog()
        this.fetchDepartment()
      })
    },
    // 获取部门详情
    async getDetail() {
      const res = await getDepartDetail(this.nodeData.id)
      this.departForm = res
      console.log(res)
    }
  }
}
</script>
